package 树;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xecaj6/
 */
public class 二叉树中序遍历 {
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val,TreeNode left,TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private List<Integer> list = new ArrayList<>();

    //递归
    public List<Integer> inorderTraversal(TreeNode root) {
        if(root == null) return new ArrayList<>();

        inorderTraversal(root.left);
        list.add(root.val);
        inorderTraversal(root.right);

        return list;

    }

    //非递归
    public List<Integer> inorderTraversalNR(TreeNode root) {
        if (root == null) return new ArrayList<>();
        TreeNode node = root;
        Stack<TreeNode> stack = new Stack<>();
        while(true){
            if(node!=null){
                stack.push(node);
                node = node.left;
            }else if(stack.empty()){
                break;
            }else{
                node = stack.pop();
                list.add(node.val);
                node = node.right;
            }
        }
        return list;
    }
}
